package com.msgserver.mbeans;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationCase;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Inject;

import org.primefaces.component.dialog.Dialog;
import org.primefaces.context.RequestContext;

import com.msgserver.ejb.services.CompanyServiceLocal;
import com.msgserver.entity.AdminRole;
import com.msgserver.entity.Company;
import com.msgserver.entity.CompanyAdmin;
import com.msgserver.entity.Contract;
import com.msgserver.entity.EmployeeGroup;
import com.msgserver.utils.MsgServerUtils;
import com.msgserver.utils.UtilConstants;
import com.ocpsoft.pretty.faces.annotation.URLMapping;
import com.ocpsoft.pretty.faces.application.PrettyRedirector;

@ManagedBean
@ViewScoped
@URLMapping(id = "superadmin", pattern = "/adminCompany", viewId = "/pages/superadmin.jsf")
public class SuperAdminBean implements UtilConstants{

	@EJB(mappedName="MsgServer_EAR/CompanyService/local-com.msgserver.ejb.services.CompanyServiceLocal")
	private CompanyServiceLocal companyService;
	private List<Company> companies = new ArrayList<Company>();
	private Company selectedCompany;
	private Company selected;
	private CompanyAdmin newAdmin = new CompanyAdmin();
	@ManagedProperty(value = "#{globalBean}")
	private GlobalBean gBean;
	
	private String newCompanyName, city, address, adminName, adminPhone, adminEmail, login, password;
	private Boolean suspended;
	private int number, numberLeft;
	private String x_eid, x_uid, x_pwd;
		
	@PostConstruct
	private void init(){
		if(gBean.getAdmin() == null || !gBean.getAdmin().getRole().equals(AdminRole.SUPER_ADMIN)){
			//if session invalid, redirect to login page
			ConfigurableNavigationHandler nav = (ConfigurableNavigationHandler) FacesContext.getCurrentInstance().getApplication().getNavigationHandler();
			nav.performNavigation("validationRequiredToSuperAdmin");
			return;
		}
		companies = companyService.loadAllCompanies();
	}
	
	public void addNewCompany(){
		if(getNumber()<=MINIMAL_NUMBER){
		    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"购买条数必须大于10000",null));  		
		    return;
		}
		if(isCompanyNameExist(getNewCompanyName())){
		    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"公司已经存在",null));  		
		    return;
		}
		Company newCompany = new Company();
		newCompany.setAddress(getAddress());
		newCompany.setCity(getCity());
		newCompany.setCompanyName(getNewCompanyName());
		CompanyAdmin admin = getNewAdmin();
		Set<CompanyAdmin> admins = new HashSet<CompanyAdmin>();
		Set<EmployeeGroup> groups = new HashSet<EmployeeGroup>();
		admin.setLogin(getLogin());
		admin.setMail(getAdminEmail());
		admin.setCompany(newCompany);
		admin.setName(getAdminName());
		admin.setPhone(getAdminPhone());
		admin.setPassword(MsgServerUtils.generateRandomPassword(8));
		admin.setRole(AdminRole.ADMIN_OF_COMPANY);
		admins.add(admin);
		EmployeeGroup defaultGroup = new EmployeeGroup();
		defaultGroup.setName(DEFAULT_GROUP);
		defaultGroup.setCompany(newCompany);
		groups.add(defaultGroup);
		newCompany.setAdmins(admins);
		newCompany.setGroups(groups);
		Contract con = new Contract();
		con.setNumber(getNumber());
		con.setX_eid(getX_eid());
		con.setX_pwd(getX_pwd());
		con.setX_uid(getX_uid());
		newCompany.setContract(con);
		companies.add(companyService.persistCompany(newCompany));
		RequestContext context = RequestContext.getCurrentInstance();
		context.getCallbackParams().clear();
		context.getCallbackParams().put("success", true);
	    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"新客户添加成功，用户名 : "+getLogin()+", 密码 : "+admin.getPassword(),null));  		

	}
	
	public void getSelectedCompanyData(ActionEvent e){
		Company companySelected = (Company) e.getComponent().getAttributes().get("selectedCompany");
		setSelectedCompany(companySelected);
		setNewCompanyName(companySelected.getCompanyName());
		setAddress(companySelected.getAddress());
		setCity(companySelected.getCity());
		CompanyAdmin admin = companySelected.getAdmins().iterator().next();
		setAdminEmail(admin.getMail());
		setAdminName(admin.getName());
		setAdminPhone(admin.getPhone());
		Contract ctr = companySelected.getContract();
		setNumber(ctr.getNumber());
		setNumberLeft(ctr.getNumber() - ctr.getNumberBeenUsed());
		setSuspended(ctr.getSuspended());
		setX_eid(ctr.getX_eid());
		setX_uid(ctr.getX_uid());
		setLogin(admin.getLogin());
		setX_pwd(ctr.getX_pwd());
	}
	
	
	public void deleteCompany(){
		Company companyToDel = getSelectedCompany();
		getCompanies().remove(companyToDel);
		companyService.deleteCompany(companyToDel);
	    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"客户 "+companyToDel.getCompanyName()+" 删除成功",null));  		
	}
	
	private boolean isCompanyNameExist(String name){
		for(Company c :getCompanies()){
			if(c.getCompanyName().equals(name)){
				return true;
			}
		}
		return false;
	}
	
	public void numberValidator(FacesContext context, UIComponent composant, Object objet){
		String number = (String) objet;
		System.out.println(number);
	}
	
	

	public List<Company> getCompanies() {
		return companies;
	}

	public void setCompanies(List<Company> companies) {
		this.companies = companies;
	}

	public CompanyAdmin getNewAdmin() {
		return newAdmin;
	}

	public void setNewAdmin(CompanyAdmin newAdmin) {
		this.newAdmin = newAdmin;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getAdminName() {
		return adminName;
	}

	public void setAdminName(String adminName) {
		this.adminName = adminName;
	}

	public String getAdminPhone() {
		return adminPhone;
	}

	public void setAdminPhone(String adminPhone) {
		this.adminPhone = adminPhone;
	}

	public String getAdminEmail() {
		return adminEmail;
	}

	public void setAdminEmail(String adminEmail) {
		this.adminEmail = adminEmail;
	}

	public String getNewCompanyName() {
		return newCompanyName;
	}

	public void setNewCompanyName(String newCompanyName) {
		this.newCompanyName = newCompanyName;
	}

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	public String getX_eid() {
		return x_eid;
	}

	public void setX_eid(String x_eid) {
		this.x_eid = x_eid;
	}

	public String getX_uid() {
		return x_uid;
	}

	public void setX_uid(String x_uid) {
		this.x_uid = x_uid;
	}

	public String getX_pwd() {
		return x_pwd;
	}

	public void setX_pwd(String x_pwd) {
		this.x_pwd = x_pwd;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Company getSelectedCompany() {
		return selectedCompany;
	}

	public void setSelectedCompany(Company selectedCompany) {
		this.selectedCompany = selectedCompany;
	}

	public Company getSelected() {
		return selected;
	}

	public void setSelected(Company selected) {
		this.selected = selected;
	}

	public GlobalBean getgBean() {
		return gBean;
	}

	public void setgBean(GlobalBean gBean) {
		this.gBean = gBean;
	}

	public Boolean getSuspended() {
		return suspended;
	}

	public void setSuspended(Boolean suspended) {
		this.suspended = suspended;
	}

	public int getNumberLeft() {
		return numberLeft;
	}

	public void setNumberLeft(int numberLeft) {
		this.numberLeft = numberLeft;
	}

	

	
}
